<?php

namespace App\Models;

use Database\Factories\PostFactory;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;

/**
 * App\Models\Post
 *
 * @property int $id
 * @property string $title
 * @property int $user_id
 * @property string $content
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property-read Collection|Comment[] $comments
 * @property-read int|null $comments_count
 * @property-read Comment|null $latestComment
 * @property-read Comment|null $oldestComment
 * @method static PostFactory factory(...$parameters)
 * @method static Builder|Post newModelQuery()
 * @method static Builder|Post newQuery()
 * @method static Builder|Post query()
 * @method static Builder|Post whereContent($value)
 * @method static Builder|Post whereCreatedAt($value)
 * @method static Builder|Post whereId($value)
 * @method static Builder|Post whereTitle($value)
 * @method static Builder|Post whereUpdatedAt($value)
 * @method static Builder|Post whereUserId($value)
 * @mixin Eloquent
 */
class Post extends Model
{
    use HasFactory, HasDateTimeFormatter;

    /**
     * 获取这篇博客所有评论
     */
    public function comments()
    {
        // Eloquent 会默认给 Comment 增加一个外键，通常这个外键是父模型的 [蛇形命名] 方法，然后再加上 _id 的方法来命名的。
        // 一次在本次示例中，Comment 模型的外加是 post_id。
        return $this->hasMany(Comment::class);
    }

    /**
     *  获取博客最新的评论
     */
    public function latestComment()
    {
        return $this->hasOne(Comment::class)->latestOfMany();
    }

    /**
     *  获取博客最早的评论
     */
    public function oldestComment()
    {
        return $this->hasOne(Comment::class)->oldestOfMany();
    }
}
